// --- Copyright (c) 2006-2008 Stefan Kyntchev ---
// This software is written and copyrighted by Stefan Kyntchev 
// and BeyondPod Team members. All rights are reserved.
// Author contact: support@beyondpod.mobi
// ------------------------------------------------------------------------
// This file is part of BeyondPod RSS Feed Reader and Podcast manager
// (www.codeplex.com/BeyondPod) 
// BeyondPod is free software: you can redistribute it and/or modify 
// it under the terms of the GNU General Public License as published by 
// the Free Software Foundation, either version 3 of the License, or 
// (at your option) any later version. 
//  
// BeyondPod is distributed in the hope that it will be useful, 
// but WITHOUT ANY WARRANTY; without even the implied warranty of 
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
// GNU General Public License for more details. 
//  
// You should have received a copy of the GNU General Public License
// along with BeyondPod. If not, see <http://www.gnu.org/licenses/>
// ------------------------------------------------------------------------
// COPYRIGHT NOTICE: This copyright notice may NOT be removed, obscured or modified 
// without written consent from the author.
// --- End copyright notice --- 


using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;
using svs.Mobile.BeyondScheduler.Core.Objects.Operations.OperationUIs;

namespace svs.Mobile.BeyondScheduler.Core.Objects.Operations
{
	public class OperationStartApplication : OperationBase, IEquatable<OperationStartApplication>
	{
		public static readonly Guid OperationID = new Guid("{E091E0B4-D0A5-4826-997B-4B083188FD86}");
		public string _ApplicationPath;
		public string _Arguments;
		public OperationStartApplication()
			: base("Start Application", "Start Application", OperationID)
		{
		}

		/// <summary>
		/// Serilized state of teh Operation
		/// </summary>
		public override string SerializedData
		{
			get { return string.Format("{0}|{1}", ApplicationPath, Arguments); }
		}


		public string ApplicationPath
		{
			get { return _ApplicationPath; }
			set
			{
				if (!string.IsNullOrEmpty(value) && File.Exists(value))
					_ApplicationPath = value;
				else
					_ApplicationPath = null;
			}
		}

		public string Arguments
		{
			get { return _Arguments; }
			set { _Arguments = value; }
		}

		/// <summary>
		/// True if the Operation has any configuration UI
		/// </summary>
		public override bool IsConfigurable
		{
			get { return true; }
		}


		public override string Name
		{
			get
			{
				string name = GetApplicationName();
				if(string.IsNullOrEmpty(name))
				  return base.Name;
				else
				{
					return string.Format("Start '{0}'", name);
				}
			}
		}

		#region IEquatable<OperationStartApplication> Members

		public bool Equals(OperationStartApplication operation)
		{
			if (operation == null) return false;
			return true;
		}

		#endregion

		public override void Execute()
		{
			base.Execute();

			//Make sure the device does not turn off on us
			CoreHelper.SetDevicePowerState(CoreHelper.PowerState.Unattended);

				StartApplication();
		}

		private void StartApplication()
		{
			if (string.IsNullOrEmpty(ApplicationPath))
			{
				CoreHelper.WriteLogEntry("Unable to execute " + _Name + " Application path does not exist!");
				return;
			}

			Process myProcess = new Process();
			try
			{
				// Get the path that stores user documents.
				myProcess.StartInfo.FileName = ApplicationPath;

				if (!string.IsNullOrEmpty(Arguments))
				{
					myProcess.StartInfo.Arguments = Arguments;
				}

				myProcess.Start();
			}
			catch (Win32Exception ex)
			{
				CoreHelper.WriteLogEntry("Unable to execute " + _Name + " Reason: " + ex.Message);
			}
		}

		private string GetApplicationName()
		{
			if (string.IsNullOrEmpty(ApplicationPath))
				return null;

			int pos = ApplicationPath.LastIndexOf(@"\");
			if (pos >= 0)
				return ApplicationPath.Substring(pos + 1);

			return null;
		}

		/// <summary>
		/// Creates an instance of the this operation, desrialized from the serilaized string
		/// </summary>
		/// <param name="serializadData"></param>
		/// <returns></returns>
		public override OperationBase CreateInstance(string serializadData)
		{
			char[] dels = {'|'};

			string[] pars = serializadData.Split(dels);

			OperationStartApplication retVal = new OperationStartApplication();

			if (pars.Length > 0)
			{
				retVal._ApplicationPath = pars[0];
			}
			if (pars.Length > 1)
			{
				retVal._Arguments = pars[1];
			}
			return retVal;
		}

		public override bool Equals(object obj)
		{
			if (ReferenceEquals(this, obj)) return true;
			return Equals(obj as OperationStartApplication);
		}

		public override int GetHashCode()
		{
			return 0;
		}

		/// <summary>
		/// UI to configure the specific actions for thhis opertation
		/// </summary>
		public override void ShowConfigurationUI(Control parentUI)
		{
			OperationStartApplicationUI ui = new OperationStartApplicationUI();
			ui.Application.Text = ApplicationPath ?? String.Empty;
			ui.Arguments.Text = Arguments ?? String.Empty;

			if(ui.ShowDialog() == DialogResult.OK)
			{
				ApplicationPath = ui.Application.Text;
				Arguments = ui.Arguments.Text;
			}
		}
	}
}